package com.eshop.modules.security.rest;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import com.eshop.modules.aop.ForbidSubmit;
import java.util.Iterator;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.Set;
import com.eshop.logging.aop.log.Log;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.RequestParam;
import com.eshop.modules.security.service.OnlineUserService;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping({ "/auth/online" })
@Api(tags = { "系统：在线用户管理" })
public class OnlineController
{
    private final OnlineUserService onlineUserService;
    
    public OnlineController(final OnlineUserService onlineUserService) {
        this.onlineUserService = onlineUserService;
    }
    
    @ApiOperation("查询在线用户")
    @GetMapping
    @PreAuthorize("@el.check('auth_online')")
    public ResponseEntity<Object> getAll(@RequestParam(value = "filter", defaultValue = "") final String filter, @RequestParam(value = "type", defaultValue = "0") final int type, final Pageable pageable) {
        return new ResponseEntity(this.onlineUserService.getAll(filter, type, pageable), HttpStatus.OK);
    }
    
    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping({ "/download" })
    @PreAuthorize("@el.check()")
    public void download(final HttpServletResponse response, @RequestParam(value = "filter", defaultValue = "") final String filter, @RequestParam(value = "type", defaultValue = "0") final int type) throws IOException {
        this.onlineUserService.download(this.onlineUserService.getAll(filter, type), response);
    }
    
    @ForbidSubmit
    @ApiOperation("踢出用户")
    @DeleteMapping
    @PreAuthorize("@el.check()")
    public ResponseEntity<Object> delete(@RequestBody final Set<String> keys) throws Exception {
        for (final String key : keys) {
            this.onlineUserService.kickOut(key);
        }
        return new ResponseEntity(HttpStatus.OK);
    }
    
    @ForbidSubmit
    @ApiOperation("踢出移动端用户")
    @PostMapping({ "/delete" })
    @PreAuthorize("@el.check()")
    public ResponseEntity<Object> deletet(@RequestBody final Set<String> keys) throws Exception {
        for (final String key : keys) {
            this.onlineUserService.kickOutT(key);
        }
        return new ResponseEntity(HttpStatus.OK);
    }
}
